<template>
  <div class="search-page">
    <!-- 搜索头部 -->
    <div class="search-header">
      <div class="search-container">
        <SearchBox
          ref="searchBoxRef"
          :placeholder="'搜索民法典条文...'"
          :show-suggestions="true"
          :show-history="true"
          @search="handleSearch"
          @clear="handleClear"
        />
      </div>
    </div>
    
    <!-- 搜索结果区域 -->
    <div class="search-content">
      <!-- 搜索信息栏 -->
      <div
        v-if="hasSearched"
        class="search-info"
      >
        <div class="search-stats">
          <span
            v-if="searchQuery"
            class="search-query"
          >
            搜索 "{{ searchQuery }}"
          </span>
          <span
            v-if="searchInfo.result_count !== undefined"
            class="search-count"
          >
            找到 {{ searchInfo.result_count }} 条结果
          </span>
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div
        v-if="loading"
        class="loading-section"
      >
        <LoadingSpinner
          size="large"
          text="搜索中..."
        />
      </div>
      
      <!-- 搜索结果列表 -->
      <div
        v-else-if="hasResults"
        class="results-section"
      >
        <div class="results-list">
          <ArticleCard
            v-for="article in searchResults"
            :key="article.article_number"
            :article="article"
            :show-explanation="true"
            :show-favorite="true"
            @click="handleArticleClick"
            @favorite-toggle="handleFavoriteToggle"
            @keyword-click="handleKeywordSearch"
          />
        </div>
        
        <!-- 分页组件 -->
        <Pagination
          v-if="pagination.pages > 1"
          :current-page="pagination.page"
          :total-pages="pagination.pages"
          :total="pagination.total"
          :page-size="pagination.per_page"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
      </div>
      
      <!-- 无结果状态 -->
      <div
        v-else-if="hasSearched && !loading"
        class="no-results"
      >
        <div class="no-results-content">
          <MagnifyingGlassIcon class="no-results-icon" />
          <h3 class="no-results-title">
            未找到相关结果
          </h3>
          <p class="no-results-text">
            尝试使用不同的关键词或检查拼写
          </p>
        </div>
      </div>
      
      <!-- 初始状态 - 搜索历史和热门搜索 -->
      <div
        v-else
        class="initial-state"
      >
        <!-- 搜索历史 -->
        <div
          v-if="hasSearchHistory"
          class="history-section"
        >
          <div class="section-header">
            <h3 class="section-title">
              搜索历史
            </h3>
            <button
              class="clear-btn"
              @click="clearSearchHistory"
            >
              清空
            </button>
          </div>
          <div class="history-list">
            <button
              v-for="item in searchHistory"
              :key="item.query"
              class="history-item"
              @click="handleHistoryClick(item.query)"
            >
              <ClockIcon class="history-icon" />
              <span class="history-query">{{ item.query }}</span>
              <span class="history-count">{{ item.result_count }}条</span>
            </button>
          </div>
        </div>
        
        <!-- 热门搜索 -->
        <div class="popular-section">
          <h3 class="section-title">
            热门搜索
          </h3>
          <div class="popular-tags">
            <button
              v-for="tag in popularTags"
              :key="tag"
              class="popular-tag"
              @click="handlePopularTagClick(tag)"
            >
              {{ tag }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MagnifyingGlassIcon, ClockIcon } from '@heroicons/vue/24/outline'
import SearchBox from '@/components/search/SearchBox.vue'
import ArticleCard from '@/components/article/ArticleCard.vue'
import Pagination from '@/components/common/Pagination.vue'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
import { useArticleStore } from '@/stores/article'
import { logger } from '@/utils/logger'

const route = useRoute()
const router = useRouter()
const articleStore = useArticleStore()

// 响应式数据
const searchBoxRef = ref(null)
const hasSearched = ref(false)

const popularTags = ref([
  '合同', '物权', '婚姻', '继承', '侵权', '人格权', '债权',
  '担保', '买卖', '租赁', '借款', '委托', '保险', '劳动'
])

// 计算属性
const searchQuery = computed(() => articleStore.searchQuery)
const searchResults = computed(() => articleStore.searchResults)
const searchInfo = computed(() => articleStore.searchInfo)
const pagination = computed(() => articleStore.pagination)
const searchHistory = computed(() => articleStore.searchHistory)
const loading = computed(() => articleStore.loading)

const hasResults = computed(() => searchResults.value.length > 0)
const hasSearchHistory = computed(() => searchHistory.value.length > 0)

// 事件处理
const handleSearch = async (query) => {
  if (!query.trim()) return
  
  try {
    hasSearched.value = true
    await articleStore.searchArticles(query, 1, pagination.value.per_page)
    
    // 更新URL
    if (route.query.q !== query) {
      router.replace({
        name: 'Search',
        query: { q: query }
      })
    }
    
    logger.userAction('执行搜索', { query, resultCount: searchResults.value.length })
  } catch (error) {
    logger.error('搜索失败:', error)
  }
}

const handleClear = () => {
  hasSearched.value = false
  router.replace({ name: 'Search' })
}

const handlePageChange = async (page) => {
  if (!searchQuery.value) return
  
  try {
    await articleStore.searchArticles(
      searchQuery.value, 
      page, 
      pagination.value.per_page
    )
    
    // 滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' })
  } catch (error) {
    logger.error('翻页失败:', error)
  }
}

const handlePageSizeChange = async (pageSize) => {
  if (!searchQuery.value) return
  
  try {
    await articleStore.searchArticles(searchQuery.value, 1, pageSize)
  } catch (error) {
    logger.error('修改页面大小失败:', error)
  }
}

const handleArticleClick = (article) => {
  router.push({
    name: 'Article',
    params: { id: article.article_number }
  })
}

const handleFavoriteToggle = async ({ article, favorited }) => {
  try {
    if (favorited) {
      await articleStore.addToFavorites(article)
    } else {
      await articleStore.removeFromFavorites(article.article_number)
    }
  } catch (error) {
    logger.error('收藏操作失败:', error)
  }
}

const handleKeywordSearch = (keyword) => {
  handleSearch(keyword)
}

const handleHistoryClick = (query) => {
  handleSearch(query)
}

const handlePopularTagClick = (tag) => {
  handleSearch(tag)
}

const clearSearchHistory = async () => {
  try {
    await articleStore.clearSearchHistory()
    logger.userAction('清空搜索历史')
  } catch (error) {
    logger.error('清空搜索历史失败:', error)
  }
}

// 监听路由查询参数
watch(() => route.query.q, async (newQuery) => {
  if (newQuery && newQuery !== searchQuery.value) {
    await handleSearch(newQuery)
  }
}, { immediate: true })

// 生命周期
onMounted(async () => {
  logger.userAction('访问搜索页面')
  
  // 如果URL中有查询参数，执行搜索
  if (route.query.q) {
    await handleSearch(route.query.q)
  }
})
</script>

<style scoped>
.search-page {
  @apply min-h-screen bg-gray-50;
}

.search-header {
  @apply bg-white border-b border-gray-200 sticky top-0 z-10;
  @apply shadow-sm;
}

.search-container {
  @apply max-w-4xl mx-auto p-4;
}

.search-content {
  @apply max-w-4xl mx-auto p-4;
}

.search-info {
  @apply mb-6;
}

.search-stats {
  @apply flex flex-wrap items-center gap-4 mb-4;
  @apply text-sm text-gray-600;
}

.search-query {
  @apply font-medium text-gray-900;
}

.search-count {
  @apply text-blue-600;
}

.loading-section {
  @apply flex justify-center py-12;
}

.results-section {
  @apply space-y-4;
}

.results-list {
  @apply space-y-4 mb-8;
}

.no-results {
  @apply flex justify-center py-12;
}

.no-results-content {
  @apply text-center max-w-md;
}

.no-results-icon {
  @apply w-16 h-16 mx-auto mb-4 text-gray-400;
}

.no-results-title {
  @apply text-xl font-semibold text-gray-900 mb-2;
}

.no-results-text {
  @apply text-gray-600 mb-6;
}

.initial-state {
  @apply space-y-8;
}

.history-section,
.popular-section {
  @apply bg-white rounded-lg p-6 shadow-sm;
}

.section-header {
  @apply flex items-center justify-between mb-4;
}

.section-title {
  @apply text-lg font-semibold text-gray-900;
}

.clear-btn {
  @apply text-sm text-red-600 hover:text-red-800;
}

.history-list {
  @apply space-y-2;
}

.history-item {
  @apply w-full flex items-center p-3 hover:bg-gray-50;
  @apply rounded-lg transition-colors text-left;
}

.history-icon {
  @apply w-4 h-4 text-gray-400 mr-3 flex-shrink-0;
}

.history-query {
  @apply flex-1 text-gray-900;
}

.history-count {
  @apply text-sm text-gray-500;
}

.popular-tags {
  @apply flex flex-wrap gap-3;
}

.popular-tag {
  @apply px-4 py-2 bg-blue-100 hover:bg-blue-200;
  @apply text-blue-800 rounded-full text-sm font-medium;
  @apply transition-colors duration-200;
}
</style>
